// Excel导出工具类
class ExcelExport {
  constructor() {
    this.workbook = null
    this.worksheet = null
  }

  // 创建工作簿
  createWorkbook() {
    this.workbook = {
      SheetNames: [],
      Sheets: {}
    }
  }

  // 创建工作表
  createWorksheet(name = 'Sheet1') {
    this.worksheet = {
      '!ref': '',
      '!cols': [],
      '!rows': []
    }
    
    this.workbook.SheetNames.push(name)
    this.workbook.Sheets[name] = this.worksheet
    
    return this.worksheet
  }

  // 设置单元格值
  setCellValue(cell, value, type = 's') {
    if (!this.worksheet[cell]) {
      this.worksheet[cell] = {}
    }
    
    this.worksheet[cell].v = value
    this.worksheet[cell].t = type // s: string, n: number, b: boolean, d: date
    
    // 设置显示值
    if (type === 'd') {
      this.worksheet[cell].w = this.formatDate(value)
    } else {
      this.worksheet[cell].w = value.toString()
    }
  }

  // 设置单元格样式
  setCellStyle(cell, style = {}) {
    if (!this.worksheet[cell]) {
      this.worksheet[cell] = {}
    }
    
    this.worksheet[cell].s = {
      font: style.font || {},
      fill: style.fill || {},
      border: style.border || {},
      alignment: style.alignment || {}
    }
  }

  // 合并单元格
  mergeCells(range) {
    if (!this.worksheet['!merges']) {
      this.worksheet['!merges'] = []
    }
    
    this.worksheet['!merges'].push({
      s: this.cellToCoords(range.split(':')[0]),
      e: this.cellToCoords(range.split(':')[1])
    })
  }

  // 设置列宽
  setColumnWidth(col, width) {
    if (!this.worksheet['!cols']) {
      this.worksheet['!cols'] = []
    }
    
    const colIndex = this.columnToIndex(col)
    this.worksheet['!cols'][colIndex] = { wch: width }
  }

  // 设置行高
  setRowHeight(row, height) {
    if (!this.worksheet['!rows']) {
      this.worksheet['!rows'] = []
    }
    
    this.worksheet['!rows'][row - 1] = { hpt: height }
  }

  // 更新工作表范围
  updateRange() {
    const cells = Object.keys(this.worksheet).filter(key => key.match(/^[A-Z]+[0-9]+$/))
    
    if (cells.length === 0) {
      this.worksheet['!ref'] = 'A1:A1'
      return
    }
    
    const coords = cells.map(cell => this.cellToCoords(cell))
    const minRow = Math.min(...coords.map(c => c.r))
    const maxRow = Math.max(...coords.map(c => c.r))
    const minCol = Math.min(...coords.map(c => c.c))
    const maxCol = Math.max(...coords.map(c => c.c))
    
    this.worksheet['!ref'] = `${this.coordsToCell(minCol, minRow)}:${this.coordsToCell(maxCol, maxRow)}`
  }

  // 单元格地址转坐标
  cellToCoords(cell) {
    const match = cell.match(/^([A-Z]+)([0-9]+)$/)
    if (!match) return { r: 0, c: 0 }
    
    const col = this.columnToIndex(match[1])
    const row = parseInt(match[2]) - 1
    
    return { r: row, c: col }
  }

  // 坐标转单元格地址
  coordsToCell(col, row) {
    return `${this.indexToColumn(col)}${row + 1}`
  }

  // 列字母转索引
  columnToIndex(col) {
    let result = 0
    for (let i = 0; i < col.length; i++) {
      result = result * 26 + (col.charCodeAt(i) - 64)
    }
    return result - 1
  }

  // 索引转列字母
  indexToColumn(index) {
    let result = ''
    index++
    
    while (index > 0) {
      const remainder = (index - 1) % 26
      result = String.fromCharCode(65 + remainder) + result
      index = Math.floor((index - 1) / 26)
    }
    
    return result
  }

  // 格式化日期
  formatDate(date) {
    if (!(date instanceof Date)) {
      date = new Date(date)
    }
    
    return date.toLocaleDateString('zh-CN')
  }

  // 生成情绪记录Excel
  async generateMoodRecordsExcel(records) {
    try {
      this.createWorkbook()
      this.createWorksheet('情绪记录')

      // 设置标题行
      const headers = ['日期', '时间', '心情', '情绪强度', '标签', '备注']
      headers.forEach((header, index) => {
        const cell = `${this.indexToColumn(index)}1`
        this.setCellValue(cell, header, 's')
        this.setCellStyle(cell, {
          font: { bold: true, color: { rgb: 'FFFFFF' } },
          fill: { fgColor: { rgb: '4472C4' } },
          alignment: { horizontal: 'center', vertical: 'center' }
        })
      })

      // 设置列宽
      this.setColumnWidth('A', 12) // 日期
      this.setColumnWidth('B', 10) // 时间
      this.setColumnWidth('C', 8)  // 心情
      this.setColumnWidth('D', 10) // 情绪强度
      this.setColumnWidth('E', 20) // 标签
      this.setColumnWidth('F', 30) // 备注

      // 填充数据
      records.forEach((record, index) => {
        const row = index + 2
        const date = new Date(record.date)
        
        this.setCellValue(`A${row}`, this.formatDate(date), 's')
        this.setCellValue(`B${row}`, date.toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        }), 's')
        this.setCellValue(`C${row}`, this.getMoodText(record.mood), 's')
        this.setCellValue(`D${row}`, record.intensity, 'n')
        this.setCellValue(`E${row}`, record.tags ? record.tags.join(', ') : '', 's')
        this.setCellValue(`F${row}`, record.note || '', 's')

        // 设置数据行样式
        for (let col = 0; col < headers.length; col++) {
          const cell = `${this.indexToColumn(col)}${row}`
          this.setCellStyle(cell, {
            border: {
              top: { style: 'thin', color: { rgb: 'D0D0D0' } },
              bottom: { style: 'thin', color: { rgb: 'D0D0D0' } },
              left: { style: 'thin', color: { rgb: 'D0D0D0' } },
              right: { style: 'thin', color: { rgb: 'D0D0D0' } }
            },
            alignment: { vertical: 'center' }
          })
        }
      })

      this.updateRange()
      return await this.saveExcel('情绪记录.xlsx')

    } catch (error) {
      console.error('生成Excel失败:', error)
      throw error
    }
  }

  // 生成测评结果Excel
  async generateTestResultsExcel(results) {
    try {
      this.createWorkbook()
      this.createWorksheet('测评结果')

      // 设置标题行
      const headers = ['测评日期', '测评类型', '得分', '等级', '建议']
      headers.forEach((header, index) => {
        const cell = `${this.indexToColumn(index)}1`
        this.setCellValue(cell, header, 's')
        this.setCellStyle(cell, {
          font: { bold: true, color: { rgb: 'FFFFFF' } },
          fill: { fgColor: { rgb: '70AD47' } },
          alignment: { horizontal: 'center', vertical: 'center' }
        })
      })

      // 设置列宽
      this.setColumnWidth('A', 15) // 测评日期
      this.setColumnWidth('B', 15) // 测评类型
      this.setColumnWidth('C', 8)  // 得分
      this.setColumnWidth('D', 10) // 等级
      this.setColumnWidth('E', 40) // 建议

      // 填充数据
      results.forEach((result, index) => {
        const row = index + 2
        
        this.setCellValue(`A${row}`, this.formatDate(new Date(result.date)), 's')
        this.setCellValue(`B${row}`, result.testName, 's')
        this.setCellValue(`C${row}`, result.score, 'n')
        this.setCellValue(`D${row}`, result.level, 's')
        this.setCellValue(`E${row}`, result.suggestion || '', 's')

        // 设置数据行样式
        for (let col = 0; col < headers.length; col++) {
          const cell = `${this.indexToColumn(col)}${row}`
          this.setCellStyle(cell, {
            border: {
              top: { style: 'thin', color: { rgb: 'D0D0D0' } },
              bottom: { style: 'thin', color: { rgb: 'D0D0D0' } },
              left: { style: 'thin', color: { rgb: 'D0D0D0' } },
              right: { style: 'thin', color: { rgb: 'D0D0D0' } }
            },
            alignment: { vertical: 'center' }
          })
        }
      })

      this.updateRange()
      return await this.saveExcel('测评结果.xlsx')

    } catch (error) {
      console.error('生成Excel失败:', error)
      throw error
    }
  }

  // 获取心情文本
  getMoodText(mood) {
    const moodMap = {
      1: '😢 很难过',
      2: '😔 难过',
      3: '😐 一般',
      4: '😊 开心',
      5: '😄 很开心'
    }
    return moodMap[mood] || '未知'
  }

  // 保存Excel文件
  async saveExcel(filename) {
    try {
      // 将工作簿转换为二进制数据
      const excelData = this.workbookToBinary()
      
      // 保存到临时文件
      const fs = uni.getFileSystemManager()
      const tempPath = `${uni.env.USER_DATA_PATH}/${filename}`
      
      return new Promise((resolve, reject) => {
        fs.writeFile({
          filePath: tempPath,
          data: excelData,
          encoding: 'binary',
          success: () => {
            resolve(tempPath)
          },
          fail: (error) => {
            reject(error)
          }
        })
      })

    } catch (error) {
      console.error('保存Excel失败:', error)
      throw error
    }
  }

  // 工作簿转二进制（简化版本）
  workbookToBinary() {
    // 这里应该使用专门的Excel库（如SheetJS）来生成真正的Excel文件
    // 为了演示，这里返回一个简化的CSV格式数据
    let csvContent = ''
    
    this.workbook.SheetNames.forEach(sheetName => {
      const worksheet = this.workbook.Sheets[sheetName]
      const range = worksheet['!ref']
      
      if (!range) return
      
      const [start, end] = range.split(':')
      const startCoords = this.cellToCoords(start)
      const endCoords = this.cellToCoords(end)
      
      for (let row = startCoords.r; row <= endCoords.r; row++) {
        const rowData = []
        
        for (let col = startCoords.c; col <= endCoords.c; col++) {
          const cell = this.coordsToCell(col, row)
          const cellData = worksheet[cell]
          rowData.push(cellData ? cellData.v : '')
        }
        
        csvContent += rowData.join(',') + '\n'
      }
    })
    
    return csvContent
  }

  // 分享Excel文件
  async shareExcel(filePath) {
    try {
      await uni.shareWithSystem({
        type: 'file',
        filePath: filePath,
        success: () => {
          uni.showToast({
            title: '分享成功',
            icon: 'success'
          })
        },
        fail: (error) => {
          console.error('分享失败:', error)
          uni.showToast({
            title: '分享失败',
            icon: 'error'
          })
        }
      })
    } catch (error) {
      console.error('分享Excel失败:', error)
      throw error
    }
  }
}

export default ExcelExport